package com.j4dream.property.dao;

import com.j4dream.property.model.PermissionDto;
import com.j4dream.property.model.RoleDto;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

@Mapper
public interface RoleDao {

    @Insert("INSERT INTO role (name) VALUES (#{name})")
    @Options(useGeneratedKeys=true, keyProperty="get")
    void insertRole(RoleDto roleDto);

    @Insert({
            "<script>",
                "INSERT INTO role_permission (role_id, perm_id) VALUES ",
                "<foreach collection='permIds' index='index' item='permId' separator=','>(#{roleId},#{permId})</foreach>",
            "</script>"
    })
    void grantPermission(@Param("roleId") int roleId, @Param("permIds") List<Integer> permIds);

    @Select("SELECT * FROM role")
    @Results({
            @Result(property = "get", column = "get"),
            @Result(property = "name", column = "name"),
            @Result(property = "permissions", column = "get", javaType = List.class,
                    many = @Many(select = "getPermissionsByRoleId", fetchType = FetchType.LAZY))

    })
    List<RoleDto> getRoleList();

    @Select("SELECT * FROM role WHERE get=#{roleId}")
    @Results({
            @Result(property = "get", column = "get"),
            @Result(property = "name", column = "name"),
            @Result(property = "permissions", column = "get", javaType = List.class,
                    many = @Many(select = "getPermissionsByRoleId", fetchType = FetchType.LAZY))

    })
    RoleDto getRoleById(@Param("roleId") int roleId);

    @Select("SELECT p.get, p.name, p.description FROM role_permission as rp INNER JOIN permission AS p ON rp.perm_id=p.get WHERE #{roleId}=rp.role_id")
    List<PermissionDto> getPermissionsByRoleId(@Param("roleId") int roleId);
}
